<template>
  <div class="bridge">
    <div class="bridge-left">
      <ul class="bridge-left_tag">
        <li class="current">
          <span>{{$t('module.treeManage.orgTree')}}</span>
        </li>
        <!-- <li>
          <span>常用</span>
        </li>-->
      </ul>
      <!-- tree start -->
      <div class="bridge-left_box">
        <Input v-model="searchValue" :placeholder="$t('common.inputNodeInfo')" style="width: 100%">
          <Icon type="ios-search" @click="searchHandler" slot="suffix" />
        </Input>
        <div class="bridge-left_box--wrap">
          <el-tree
            :data="treeList"
            :props="treeProps"
            icon-class="ivu-icon-ios-arrow-forward"
            @node-expand="onToggleExpand"
            @node-collapse="onToggleExpand"
            @node-click="onSelectChange"
          ></el-tree>
        </div>
      </div>
      <!-- tree end -->
    </div>
    <div class="bridge-right">
      <!-- 穿梭框 start -->
      <Transfer
        class="bridge-right_transfer"
        :data="employeeList"
        :target-keys="targetKeys"
        filterable
        :list-style="listStyle"
        :filter-method="filterMethod"
        @on-change="handleChange2"
        @on-selected-change="transferOnChange"
        :titles="['全选', '全选']"
      ></Transfer>
      <!-- 穿梭框 end -->
    </div>
  </div>
</template>
<script>
import { findTreeList, findEmployeeList, findTreeNode, filterTree } from "@api/treeApi";
import locales from "../locales.js";

export default {
   mixins: [locales],

  name: "SelectPersonBrige",
  data() {
    return {
      targetKeys: [],
      sourceSelectedKeys: [],
      // 人员集合
      employeeList: [],
      // 穿梭框样式
      listStyle: {
        height: "360px"
      },
      // 树列表集合
      treeList: [],
      treeListBak: [],
      searchValue: "",
      treeProps: {
        label: "nodeName",
        children: "children"
      }
    };
  },
  props: {
    // 查询通用树条件
    condition: {
      type: Object,
      default: () => ({
        treeCode: "",
        productCode: "",
        tenantCode: ""
      })
    },
    // 选人桥标题
    title: {
      type: String,
      default: "selectPerson"
    },
    // 点击保存处理函数
    saveHandler: {
      type: Function,
      default: _ => _
    },
    defaultPersonList: {
      type: Array,
      default: () => []
    },
    multiple: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    actions() {
      return [
        {
          text: this.$t("common.add"),
          theme: "primary",
          handle: () => {
            this.callBackWithData();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => this.$emit("Close")
        }
      ];
    }
  },
  created() {
    this.$emit("SetTitle", this.title);
    this.$emit("SetPageWidth", 530);
    this.$emit("SetPageActions", this.actions);
  },
  watch: {
    condition: {
      handler: async function(condition) {
        // const _param = { treeCode: '49c27d1e7ad511e9b28e005056a238f5' };
        // 查询通用树
        const nodeCode = window.RPConfig.node_code;
        const res = await findTreeList(nodeCode);
        this.treeList = this.formatTreeData(res.data);
        this.treeListBak = this.treeList;
      },
      immediate: true
    }
  },
  methods: {
    //临时借用这个组件, 后面再处理
    callBackWithData() {
      const { sourceSelectedKeys, employeeList } = this;
      const item = sourceSelectedKeys.map(key => {
        const { data } = employeeList.find(emp => emp.key === key);
        return data;
      });
      this.saveHandler(item, this);
    },
    // 格式化通用树数据
    formatTreeData(data = []) {
      if (!Array.isArray(data)) return [];
      return data.map(item => ({
        nodeName: item.nodeName,
        id: item.id,
        code: item.nodeCode,
        children: item.endNode == "Y" ? [] : [{}]
      }));
    },
    // 穿梭框切换处理数据
    handleChange2(newTargetKeys) {
      this.targetKeys = newTargetKeys;
    },
    // 穿梭框搜索筛选函数
    filterMethod(data, query) {
      return data.label && data.label.indexOf(query) > -1;
    },
    async searchHandler() {
      const { searchValue } = this;
      if (searchValue == "") {
        this.treeList = this.treeListBak;
        return;
      }
      // searchValue
      const nodeCode = window.RPConfig.node_code;
      const res = await filterTree({ pageSize: 999, pageNum: 1, condition: { nodeName: searchValue, nodeCode } });
      // debugger
      this.treeList = this.formatTreeData(res.data.records);
    },
    // 查询节点的人员
    async onSelectChange({ code, id, nodeName }) {
      // console.log(cur)
      try {
        const res = await findEmployeeList({
          pageSize: 999,
          pageNum: 1,
          condition: { departmentCode: code }
        });
        const { records = [] } = res.data;
        const { defaultPersonList } = this;
        this.employeeList = records.map(val => {
          val.departmentCode = id;
          val.departmentName = nodeName;
          const dis = defaultPersonList.find(v => v.employeeId == val.employeeNo);
          return {
            key: val.employeeNo,
            label: val.name,
            disabled: !!dis,
            data: val
          };
        });
      } catch (error) {
        console.log("err", error);
      }
    },
    // 切换树展开
    async onToggleExpand(row) {
      const { id, children = [] } = row;
      // 子节点有2条及以上数据则通过不查询
      if (children.length > 1 || !children[0] || children[0].nodeName) return;
      try {
        // 查询子节点
        const res = await findTreeNode(id);
        const children = this.formatTreeData(res.data);
        // 给当前查询节点赋予子节点
        this.$set(row, "children", children);
      } catch (error) {}
    },
    transferOnChange(skey) {
      this.sourceSelectedKeys = skey;
      if (!this.multiple) {
        this.callBackWithData();
      }
    }
  }
};
</script>
<style>
.ivu-tree li ul {
  padding: 0 0 0 10px;
}
/* 修改穿梭框样式 为隐藏操作按钮和目标框 */
.bridge-right_transfer .ivu-transfer-operation {
  display: none;
}
.bridge-right_transfer .ivu-transfer-list:last-child {
  display: none;
}

.ivu-tree-empty {
  text-align: center;
}
</style>

<style lang="less" scoped>
ul li {
  list-style: none;
}
.bridge {
  display: flex;
  height: 361px;
  &-left {
    display: flex;
    margin-right: 15px;
    &_tag {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-end;
      height: 100%;

      li {
        height: 90px;
        width: 30px;
        padding: 18px 8px;
        border: solid 1px #f1f1f1;
        border-radius: 4px;
        cursor: pointer;
        &.current {
          background-color: #ff6f4b;
          color: #fff;
        }
      }
    }
    &_box {
      height: 100%;
      width: 260px;
      border: 1px solid #f1f1f1;
      &--wrap {
        height: 360 - 32px;
        overflow-y: scroll;
      }
    }
  }
}
</style>
